#include <iostream>
#include <string.h>
#include <unistd.h>
#include <pthread.h>
#include <sched.h>
#include "Mutex.hpp"
using namespace LockModule;
int ticket = 1000;
Mutex mut;
void *Ticket(void *args)
{
    std::string name = static_cast<const char *>(args);
    // 加锁解锁有两种方式
    while (true)
    {
        // 第一种
        mut.lock();
        if (ticket > 0)
        {
            usleep(1000);
            std::cout << name << "get a ticket,ticket:" << --ticket << std::endl;
            mut.unlock();
        }
        else
        {
            mut.unlock();
            break;
        }
        // 第二种 创建临时对象以代码块的形式
        {
            // 不需要主动加锁解锁
            // LockGard的构造和析构函数自动加锁解锁了
            LockGard lockgard(mut);
            if (ticket > 0)
            {
                usleep(1000);
                std::cout << name << "get a ticket,ticket:" << --ticket << std::endl;
            }
            else
            {
                break;
            }
        }
    }

    return nullptr;
}
int main()
{
    pthread_t th1, th2, th3, th4;
    pthread_create(&th1, nullptr, Ticket, (void *)"thread1");
    pthread_create(&th2, nullptr, Ticket, (void *)"thread2");
    pthread_create(&th3, nullptr, Ticket, (void *)"thread3");
    pthread_create(&th4, nullptr, Ticket, (void *)"thread4");

    int cnt = 10;
    while (true)
    {
        sleep(1);
        std::cout << "主线程放票了" << std::endl;
        ticket += 1000;
    }

    pthread_join(th1, nullptr);
    pthread_join(th2, nullptr);
    pthread_join(th3, nullptr);
    pthread_join(th4, nullptr);
    return 0;
}